<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Protocol Converter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      background-color: #3c3b3b;
    }
    .container {
      background-color: white;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      margin-top: 40px;
    }
    h1 {
      color: #333;
      text-align: center;
    }
    .upload-area {
      border: 2px dashed #ccc;
      padding: 40px;
      text-align: center;
      margin: 20px 0;
      border-radius: 5px;
      cursor: pointer;
      transition: all 0.3s;
    }
    .upload-area:hover {
      border-color: #666;
      background-color: #f9f9f9;
    }
    .btn {
      background-color: #4CAF50;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 16px;
      margin-top: 10px;
    }
    .btn:hover {
      background-color: #45a049;
    }
    .status {
      margin-top: 20px;
      padding: 10px;
      border-radius: 4px;
    }
    .progress {
      width: 100%;
      background-color: #ddd;
      border-radius: 4px;
      margin-top: 20px;
    }
    .progress-bar {
      height: 20px;
      background-color: #4CAF50;
      border-radius: 4px;
      width: 0%;
      transition: width 0.3s;
    }
    .download-link {
      display: none;
      margin-top: 20px;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Protocol Converter</h1>
    <p>Upload your document to convert it to the required format.</p>
    
    <div class="upload-area" id="dropArea">
      <p>Drag & drop your file here or click to select</p>
      <input type="file" id="fileInput" style="display: none;" accept=".doc,.docx">
      <el-button type="primary" id="selectBtn">Select File</el-button>
    </div>
    <div style="margin-top: 20px; text-align: center;">
      <el-button type="success" id="runScriptBtn">Run Conversion Script</el-button>
    </div>
    <div class="progress" style="display: none;">
      <div class="progress-bar" id="progressBar"></div>
    </div>
    
    <div class="status" id="status"></div>
    
    <div class="download-link" id="downloadLink">
      <p>Your file is ready!</p>
      <el-button type="primary" id="downloadBtn">Download Converted File</el-button>
    </div>
  </div>

  <script>
    const dropArea = document.getElementById('dropArea');
    const fileInput = document.getElementById('fileInput');
    const selectBtn = document.getElementById('selectBtn');
    const progressBar = document.getElementById('progressBar');
    const progressContainer = document.querySelector('.progress');
    const statusDiv = document.getElementById('status');
    const downloadLink = document.getElementById('downloadLink');
    const downloadBtn = document.getElementById('downloadBtn');
    document.addEventListener('DOMContentLoaded', () => {
      if (htmlUIAPI) {
        htmlUIAPI.injectWindowControls();
      }
    });
    document.getElementById('runScriptBtn').addEventListener('click', async () => {
        statusDiv.innerHTML = '正在执行脚本...';
        statusDiv.style.color = '#333';
        statusDiv.style.display = 'block';
        
        try {
          const fileName = 'protocol-convert';
          // 明确传递空对象而不是undefined
          const result = await pyAPI.runpyfile({fileName: fileName});
          
          if (result && result.success) {
              statusDiv.innerHTML = result.message || '脚本执行成功!';
              statusDiv.style.color = 'green';
          } else {
              const errorMsg = result?.error || '未知错误';
              throw new Error(errorMsg);
          }
        } catch (error) {
          console.error('脚本执行错误:', error);
          statusDiv.innerHTML = `执行脚本出错: ${error.message}`;
          statusDiv.style.color = 'red';
        }
    });


    // 点击选择文件
    selectBtn.addEventListener('click', () => {
      fileInput.click();
    });
    
    // 文件选择变化
    fileInput.addEventListener('change', (e) => {
      if (e.target.files.length > 0) {
        uploadFile(e.target.files[0]);
      }
    });
    
    // 拖放功能
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
      dropArea.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
      e.preventDefault();
      e.stopPropagation();
    }
    
    ['dragenter', 'dragover'].forEach(eventName => {
      dropArea.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
      dropArea.addEventListener(eventName, unhighlight, false);
    });
    
    function highlight() {
      dropArea.style.borderColor = '#4CAF50';
      dropArea.style.backgroundColor = '#e8f5e9';
    }
    
    function unhighlight() {
      dropArea.style.borderColor = '#ccc';
      dropArea.style.backgroundColor = '';
    }
    
    // 处理文件拖放
    dropArea.addEventListener('drop', (e) => {
      const dt = e.dataTransfer;
      const file = dt.files[0];
      if (file) {
        uploadFile(file);
      }
    });
    
    // 上传文件
    async function uploadFile(file) {
      console.log(file);
      // 检查文件类型
      if (!file.name.match(/\.(doc|docx)$/i)) {
        statusDiv.innerHTML = 'Please upload a Word document (.doc or .docx)';
        statusDiv.style.color = 'red';
        return;
      }
      
      // 定义interval变量
      let interval;
      progressContainer.style.display = 'block';
      statusDiv.innerHTML = 'Processing file...';
      statusDiv.style.color = '#333';

      // 模拟进度
      let progress = 0;
      interval = setInterval(() => {
        progress += 5;
        progressBar.style.width = `${progress}%`;
        if (progress >= 100) clearInterval(interval);
      }, 200);

      try {
        // 使用FileReader读取文件内容
        const reader = new FileReader();
        
        // 使用Promise包装FileReader
        const fileContent = await new Promise((resolve, reject) => {
          reader.onload = () => resolve(reader.result);
          reader.onerror = () => reject(new Error('文件读取失败'));
          reader.readAsArrayBuffer(file);
        });
        
        // 创建Uint8Array以便传递给saveTempFile
        const uint8Array = new Uint8Array(fileContent);
        
        // 保存到临时文件并获取路径
        const fullPath = await fileAPI.saveTempFile(file.name, uint8Array);

        if (!fullPath) {
            throw new Error('无法创建临时文件');
        }

        const result = await window.pyAPI.runProtocolConvert({
            filePath: fullPath,
            fileName: file.name
        });
        
        clearInterval(interval);
        progressBar.style.width = '100%';
        
        if (result.success) {
          statusDiv.innerHTML = 'File processed successfully!';
          statusDiv.style.color = 'green';
          
          downloadLink.style.display = 'block';
          downloadBtn.onclick = () => {
            electronAPI.downloadFile(result.outputPath);
          };
        } else {
          throw new Error(result.error || 'Unknown error');
        }
      } catch (error) {
        clearInterval(interval);
        statusDiv.innerHTML = '处理文件失败: ' + error.message;
        statusDiv.style.color = 'red';
      }
    }
  </script>
</body>
</html>
